package com.theanh.RssActivity.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import com.theanh.RssActivity.R;
import com.theanh.RssActivity.Store;
import com.theanh.RssActivity.db.DbAdapter;
import com.theanh.RssActivity.entity.Category;
import com.theanh.RssActivity.iconlist.IconText;
import com.theanh.RssActivity.iconlist.IconTextListAdapter;
import com.theanh.RssActivity.iconlist.IconTextView;
import com.theanh.RssActivity.ui.adapter.CategoryAdapter;
import com.theanh.RssActivity.ui.model.CategoryModel;
import com.theanh.RssActivity.updater.DbCleaner;
import com.theanh.RssActivity.util.DbUtils;
import com.theanh.RssActivity.util.DialogUtils;
import com.theanh.RssActivity.util.ImageView;
import com.theanh.RssActivity.util.Utils;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Dialog;
import android.widget.TextView;
import java.net.URLEncoder;

public class ListCategoryScreen extends ListActivity {
	public static final String TAG = "CategoryScreen";
	private static final int UPDATE_CATEGORY_MESSAGE = 1;
	private static final int ADD_CATEGORY = Menu.FIRST;
	private static final int EDIT_CATEGORY = Menu.FIRST + 1;
	private static final int DELETE_CATEGORY = Menu.FIRST + 2;
	private static final int SETTING = Menu.FIRST + 3;
	private static final int ABOUT = Menu.FIRST + 4;

	private int positionFocusCategory = 0;
	List<Category> categories = new ArrayList<Category>();

	private static int[] listIconCategory;
	CategoryAdapter categoryAdapter;

	private int idIconCategory = 0;
	private MenuItem mnuAddCategory;
	private MenuItem mnuDeleteCategory;
	private MenuItem mnuEditCategory;
	private MenuItem mnuSettting;
	private MenuItem mnuAbout;
	private ImageButton btnChooseIconCategory;
	// private Button btnChooseIconCategory;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_CATEGORY_MESSAGE:
				if (categoryAdapter != null)
					categoryAdapter.categories = categories;

				// setProgressBarIndeterminateVisibility(false);
				Log.i(TAG, "invalidateViews");
				// setListAdapter(categoryAdapter);
				getListView().invalidateViews();

				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
//		DbAdapter dbAdapter
		listIconCategory = Utils.getCategoryIcons();
		// Request for the progress bar to be shown in the title
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

		// Make sure the progress bar is visible
		setProgressBarIndeterminateVisibility(true);
		
		setContentView(R.layout.list_category);

		String filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
		Log.i(TAG,"file path="+filePath);
		// Setup DB
		Store.context = this;
		Store.init();
		Log.w(TAG,"context of Store"+Store.context.toString());
		deleteItemExpired();

		// Load data
		loadData();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		finish();
	}

	// @Override
	// protected void onListItemClick(ListView l, View v, int position, long id)
	// {
	// // TODO Auto-generated method stub
	// super.onListItemClick(l, v, position, id);
	// }

	private void deleteItemExpired() {
		DbCleaner cleaner = new DbCleaner();
		cleaner.start();
	}

	private void loadData() {

		categoryAdapter = new CategoryAdapter(this, categories);

		setListAdapter(categoryAdapter);
		getListView().setItemsCanFocus(true);

		// Set default focus
		setSelection(0);

		new Thread() {
			public void sendMessage(int identifier) {
				Message message = new Message();
				message.what = identifier;

				// send data to update GUI
				handler.sendMessage(message);
			}

			public void run() {

				DbAdapter dbAdapter = null;
				try {
					// Open database
					dbAdapter = DbUtils.createAndOpenDbAdapter();
					categories = dbAdapter.getCategories();
				} catch (Exception ex) {
					Log.e(TAG, ex.toString());

					// TODO: show message dialog
				} finally {
					if (dbAdapter != null) {
						DbUtils.closeDbAdapter(dbAdapter);
					}
				}
				sendMessage(UPDATE_CATEGORY_MESSAGE);
			}
		}.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		mnuAddCategory = menu.add(0, ADD_CATEGORY, 0,
				R.string.menu_add_category_text).setIcon(R.drawable.ic_add);
		mnuDeleteCategory = menu.add(0, DELETE_CATEGORY, 1,
				R.string.menu_delete_category_text).setIcon(
				R.drawable.ic_delete);
		mnuEditCategory = menu.add(0, EDIT_CATEGORY, 2,
				R.string.menu_edit_category_text).setIcon(R.drawable.ic_edit);
		mnuSettting = menu.add(0, SETTING, 3, R.string.menu_setting_text)
				.setIcon(R.drawable.ic_setting);
		mnuAbout = menu.add(0, ABOUT, 4, R.string.about).setIcon(
				R.drawable.ic_info);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case ADD_CATEGORY:
			showAddCategory();
			break;
		case DELETE_CATEGORY:
			deleteCategory();
			break;
		case EDIT_CATEGORY:
			showEditCategory();
			break;
		case SETTING:
			Utils.showSetting();
			break;
		case ABOUT:
			showAbout();
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		if (!Store.hasCategoryFocus) {
			mnuDeleteCategory.setEnabled(false);
			mnuEditCategory.setEnabled(false);
		} else {
			mnuDeleteCategory.setEnabled(true);
			mnuEditCategory.setEnabled(true);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	private void showAddCategory() {
		try {
			// set position category selected
			positionFocusCategory = getListView().getSelectedItemPosition();

			View viewAddCategory = getLayoutInflater().inflate(
					R.layout.add_category, null);
			btnChooseIconCategory = (ImageButton) viewAddCategory
					.findViewById(R.id.btnChooseIconCategory);
			btnChooseIconCategory
					.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							chooseIconCategory();
						}
					});
			final EditText txtAddCategory = (EditText) viewAddCategory
					.findViewById(R.id.addCategoryNameTextView);
			new AlertDialog.Builder(this)
					.setTitle(R.string.dialog_add_category).setView(
							viewAddCategory).setPositiveButton(
							R.string.button_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String titleAddCategory = null;
									dialog.dismiss();
									titleAddCategory = txtAddCategory.getText()
											.toString();
									if (titleAddCategory.length() == 0) {
										DialogUtils.showToastMessage(R.string.warring_category_name_not_null);
									} else {
										addCategory(titleAddCategory,
												idIconCategory);
									}
									getListView().setSelection(
											positionFocusCategory);
									btnChooseIconCategory = null;
								}
							}).setNegativeButton(R.string.button_dialog_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButotn) {
									btnChooseIconCategory = null;
								}
							}).create().show();
		} catch (Exception ex) {
			Log.i(TAG, "error = " + ex.toString());
		}
	}

	private void showEditCategory() {
		try {
			// set position category selected
			positionFocusCategory = getListView().getSelectedItemPosition();
			View viewAddCategory = getLayoutInflater().inflate(
					R.layout.add_category, null);
			btnChooseIconCategory = (ImageButton) viewAddCategory
					.findViewById(R.id.btnChooseIconCategory);
			if (idIconCategory == 0) {
				idIconCategory = listIconCategory[1];
			}
			btnChooseIconCategory
					.setImageResource(Store.categoryModelSelected.category
							.getIconID());
			btnChooseIconCategory
					.setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							chooseIconCategory();
						}
					});
			final EditText txtAddCategory = (EditText) viewAddCategory
					.findViewById(R.id.addCategoryNameTextView);
			txtAddCategory.setText(Store.categoryModelSelected.category
					.getName());
			new AlertDialog.Builder(this).setTitle(
					R.string.dialog_edit_category).setView(viewAddCategory)
					.setPositiveButton(R.string.button_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String titleAddCategory = null;
									dialog.dismiss();
									titleAddCategory = txtAddCategory.getText()
											.toString();
									if (titleAddCategory.length() == 0) {
										DialogUtils.showToastMessage(R.string.warring_category_name_not_null);
									} else {
										editCategory(titleAddCategory);
									}
									getListView().setSelection(
											positionFocusCategory);
									btnChooseIconCategory = null;
								}
							}).setNegativeButton(R.string.button_dialog_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButotn) {
									btnChooseIconCategory = null;
								}
							}).create().show();
		} catch (Exception ex) {
			Log.i(TAG, "error = " + ex.toString());
		}
	}

	private void chooseIconCategory() {
		try {
			List<IconText> listIcon = new ArrayList<IconText>();
			final AlertDialog dialogIconCategory = new AlertDialog.Builder(this)
					.create();
			final ListView listView = new ListView(getBaseContext());
			IconTextListAdapter iconAdapter = new IconTextListAdapter(this);
			for (int i = 0; i < listIconCategory.length; i++) {
				listIcon.add(new IconText(getResources().getDrawable(
						listIconCategory[i])));
			}
			iconAdapter.setListItems(listIcon);
			listView.setAdapter(iconAdapter);
			listView
					.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						public void onItemClick(AdapterView<?> adapterView,
								View view, int position, long id) {
							idIconCategory = listIconCategory[position];
							dialogIconCategory.hide();

							// Update icon in Edit category dialog
							if (btnChooseIconCategory != null) {
								btnChooseIconCategory
										.setImageResource(idIconCategory);
							}
						}
					});
			dialogIconCategory.setTitle(R.string.dialog_choose_icon_category);
			dialogIconCategory.setView(listView);
			dialogIconCategory.show();

		} catch (Exception ex) {
			// TODO show message
			Log.e(TAG, ex.toString());
		}
	}

	private void addCategory(String name, int idIconCategry) {
		DbAdapter dbAdapter = null;
		Category category = null;
		try {
			dbAdapter = DbUtils.createAndOpenDbAdapter();
			category = new Category();
			category.setName(name);
			category.setIconID(idIconCategry);

			if (!category.validate()) {
				return;
			}
			dbAdapter.insertCategory(category);
			loadData();
		} catch (Exception ex) {
			Log.i(TAG, "error = " + ex.toString());
		} finally {
			if (dbAdapter != null) {
				DbUtils.closeDbAdapter(dbAdapter);
			}
		}
	}

	private void deleteCategory() {
		// set position category selected
		positionFocusCategory = getListView().getSelectedItemPosition();
		TextView txtWarringDeleteCategory = new TextView(getBaseContext());
		txtWarringDeleteCategory.setText(getResources().getString(
				R.string.warring_delete_category_textview)
				+ " \"" + Store.categoryModelSelected.category.getName()+"\"");
		new AlertDialog.Builder(this).setTitle(
				R.string.warring_delete_category_title).setView(
				txtWarringDeleteCategory).setPositiveButton(
				R.string.button_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						DbAdapter dbAdapter = null;
						Category category = null;
						try {
							dbAdapter = DbUtils.createAndOpenDbAdapter();
							category = new Category();
							category.setID(Store.categoryModelSelected.category
									.getID());
							dbAdapter.deleteCategory(category);
							loadData();
							getListView().setSelection(--positionFocusCategory);
						} catch (Exception ex) {
							// TODO
							Log.e(TAG, ex.toString());
						} finally {
							if (dbAdapter != null) {
								DbUtils.closeDbAdapter(dbAdapter);
							}
						}
					}
				}).setNegativeButton(R.string.button_dialog_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {

					}
				}).create().show();
	}

	private void editCategory(String name) {
		Category category = new Category();
		category.setID(Store.categoryModelSelected.category.getID());
		category.setName(name);
		category.setIconID(idIconCategory);

		if (!category.validate()) {
			// TODO: Show message dialog
			return;
		}

		DbAdapter dbAdapter = null;
		try {
			dbAdapter = DbUtils.createAndOpenDbAdapter();

			dbAdapter.updateCategory(category);
			Store.categoryModelSelected.updateName();
			Store.categoryModelSelected.category.setName(name);
			loadData();
		} catch (Exception ex) {
			// TODO
			Log.e(TAG, ex.toString());
		} finally {
			if (dbAdapter != null) {
				DbUtils.closeDbAdapter(dbAdapter);
			}
		}
	}

	private void showAbout() {
		View view = getLayoutInflater().inflate(R.layout.about, null);
		new AlertDialog.Builder(this).setTitle(R.string.about).setIcon(
				R.drawable.ic_info).setView(view).setPositiveButton(
				R.string.button_dialog_ok,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichbutton) {

					}
				}).create().show();
	}
}
